﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Linq;

namespace Controllers
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    class AuthenticationAttribute : ActionFilterAttribute
    {
        //该变量不能声明为Static,因为:ctx.LoadOptions必须在实例化前指定
        protected ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var rdto = new ResultMessages();
            rdto.Result = true;
            //var controllerName = filterContext.RouteData.Values["controller"].ToString();
            //var actionName = filterContext.RouteData.Values["action"].ToString();
            if (filterContext.HttpContext.Session["ebi"] == null && filterContext.HttpContext.Request.Cookies["empBasicInfo"] == null)
            {
                rdto.ErrType = ErrorType.UnAuthentication;//未登录
                rdto.Result = false;
            }
            else if (!_authorizeCore(filterContext))//根据验证判断进行处理
            {
                rdto.ErrType = ErrorType.UnAuthorization;//未授权
                rdto.Result = false;
            }
            if (!rdto.Result)
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string s = jss.Serialize(rdto);
                filterContext.Result = new ContentResult { Content = s };
            }
        }

        //权限判断业务逻辑
        private bool _authorizeCore(ActionExecutingContext filterContext)
        {
            bool bResult = true;
            EmpBasicInfo ebi;
            if (filterContext.HttpContext.Session["ebi"] == null)
            {
                string s = filterContext.HttpContext.Request.Cookies["empBasicInfo"].Value;//取用户基本信息
                s = CommonController.Decrypt(s, CommonController.myKey);//字符串解密
                JavaScriptSerializer jss = new JavaScriptSerializer();
                ebi = jss.Deserialize<EmpBasicInfo>(s);//对象反序列化
                filterContext.HttpContext.Session["ebi"] = ebi;

                List<int> deptTopIds=new List<int>();
                List<int> deptIdList=new List<int>();
                int empId = ebi.Id;
                IQueryable<EmpDepPosition> listEDP = from r in ctx.EmpDepPositions where r.EmpId == empId && r.PosId>=7 orderby r.PosId select r;
                var d = new DeptController();
                foreach (var edp in listEDP)
                {
                    if (deptIdList.Contains(edp.DeptId))//此部门节点已被其他部门包含
                    {
                        continue;
                    }
                    deptTopIds.Add(edp.DeptId);

                    deptIdList=deptIdList.Concat(d.GetChildDeptIdList(edp.DeptId)).ToList();
                }
                filterContext.HttpContext.Session["deptTopIds"] = deptTopIds;//顶级部门Id
                filterContext.HttpContext.Session["deptIdList"] = deptIdList;//所有部门Id
            }
            if (filterContext.HttpContext.Request.Cookies["empBasicInfo"] == null)
            {
                ebi = filterContext.HttpContext.Session["ebi"] as EmpBasicInfo;
                //保存cookie
                HttpCookie cookieEmpId = new HttpCookie("empId", ebi.Id.ToString());
                filterContext.HttpContext.Response.Cookies.Add(cookieEmpId);
                HttpCookie cookieEmpName = new HttpCookie("empName", HttpUtility.UrlEncodeUnicode(ebi.Name));
                filterContext.HttpContext.Response.Cookies.Add(cookieEmpName);
                HttpCookie cookieJobNo = new HttpCookie("jobNo",ebi.JobNo);
                filterContext.HttpContext.Response.Cookies.Add(cookieJobNo);

                JavaScriptSerializer jss = new JavaScriptSerializer();
                string ebiStr = jss.Serialize(ebi);
                ebiStr = CommonController.Encrypt(ebiStr, CommonController.myKey);//加密的用户信息
                HttpCookie cookieEBI = new HttpCookie("empBasicInfo", ebiStr);
                filterContext.HttpContext.Response.Cookies.Add(cookieEBI);
            }
            #region //根据ebi判断controller+action的可执行权限
            //var user = new CurrentUser();//获取当前用户信息
            //var controllerName = filterContext.RouteData.Values["controller"].ToString();
            //var actionName = filterContext.RouteData.Values["action"].ToString();
            //if (isViewPage && controllerName.ToLower() != "main" && actionName.ToLower() != "masterpage")//如果当前Action请求为具体的功能页并且不是MasterPage页
            //{
            //    if (user.MenuPermission.Count(m => m.ControllerName == controllerName && m.ActionName == actionName) == 0)
            //        return false;
            //}
            //else
            //{
            //    var actions = ContainerFactory.GetContainer().Resolve<IAuthorityFacade>().GetAllActionPermission();//所有被维护的Action权限
            //    if (actions.Count(a => a.ControllerName == controllerName && a.ActionName == actionName) != 0)//如果当前Action属于被维护的Action权限
            //    {
            //        if (user.ActionPermission.Count(a => a.ControllerName == controllerName && a.ActionName == actionName) == 0)
            //            return false;
            //    }
            //}
            #endregion

            return bResult;
        }

        //public override void OnActionExecuted(ActionExecutedContext filterContext)
        //{
        //}
    }
}